package com.kgc.controller;


import com.kgc.common.Result;
import com.kgc.entity.*;
import com.kgc.service.interf.ArticlesService;
import com.kgc.service.interf.NotificationsService;
import com.kgc.service.interf.PointsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


// 文章模块
@RestController
@RequestMapping("/apis/user/article")
public class ArticlesController {
    @Autowired
    private ArticlesService articlesService;

    @Autowired
    private PointsService pointsService;

    @Autowired
    private NotificationsService notificationsService;


    //查询文章
    @RequestMapping("/show")
    public String getAllArticles(String queryKey, String queryDateBegin, String queryDateEnd, Integer articleSort) {
        List<Articles> allArticle = articlesService.getAllArticle(queryKey, queryDateBegin, queryDateEnd, articleSort);
        if (allArticle != null) {
            return Result.success("0", "返回文章信息成功", allArticle);
        } else {
            return Result.success("400", "返回文章信息失败");
        }
    }

    //查询指定用户文章
    @RequestMapping("/queryById")
    public String getArticles(int userId) {
        List<Articles> allArticle = articlesService.getArticleByUserID(userId);
        if (allArticle != null) {
            return Result.success("0", "返回文章信息成功", allArticle);
        } else {
            return Result.success("400", "返回文章信息失败");
        }
    }


    // 发布文章回显文章类别
    @RequestMapping("/selectarticlesort")
    public String selectArticlesort() {
        List<ArticleSort> articleType = articlesService.getArticleType();
        System.out.println(articleType);
        if (articleType != null) {
            return Result.success("0", "返回文章类别成功", articleType);
        } else {
            return Result.success("400", "返回文章类别失败");
        }
    }



    //发布文章
    @RequestMapping("/add")
    public String addArticles(@RequestBody Articles articles) {
        //插入当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        articles.setPublishedAt(simpleDateFormat.format(new Date()));
        articles.setArticleStatus("0");//文章状态码
        int i = articlesService.addArticle(articles);// 发布文章
        //获取发布文章对应的积分
        PointsRules pointsRules = new PointsRules();
        pointsRules.setRuleName("发表文章");
        List<PointsRules> points = pointsService.getPoints(pointsRules);
        for (PointsRules rules : points) {
            // 获取每个对象中的pointsValue属性值
            int pointsValue = rules.getPointsValue();
            int ruleID = rules.getRuleID();
            // 给用户增加积分
            int i1 = pointsService.addPoints(articles.getAuthorID(), pointsValue);
            //添加积分流水
            PointsLog pointsLog = new PointsLog();
            pointsLog.setUserID(articles.getAuthorID());
            pointsLog.setRuleID(ruleID);
            pointsLog.setDescription("发表了一篇文章");
            pointsLog.setCreatedAt(simpleDateFormat.format(new Date()));
            int i2 = pointsService.addPointsFlow(pointsLog); //添加
            if (i > 0 && i1 > 0 && i2 > 0) {
                return Result.success("0", "发布文章成功！");
            } else {
                return Result.success("400", "发布文章失败！");
            }
        }
        return Result.success("400", "发布文章失败！");

    }

    //存草稿
    @RequestMapping("/adddraft")
    public String addDraft(@RequestBody Articles articles) {
        //插入当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        articles.setPublishedAt(simpleDateFormat.format(new Date()));
        articles.setArticleStatus("1"); //文章状态码
        int i = articlesService.addArticle(articles);
        if (i > 0) {
            return Result.success("0", "存入草稿箱成功！");
        } else {
            return Result.success("400", "存入草稿失败！");
        }
    }

    //用户查询草稿箱
    @RequestMapping("/getdraft")
    public String getDraft(int authorID) {
        List<Articles> allArticle = articlesService.getdraft(authorID);
        System.out.println(allArticle);
        if (allArticle.size() > 0) {
            return Result.success("0", "返回文章信息成功", allArticle);
        } else {
            return Result.success("400", "返回文章信息失败");
        }
    }

    //删除指定用户下的指定文章
    @RequestMapping("/delById")
    public String delById(@RequestParam("authorId") Integer authorId, @RequestParam("articleId") Integer articleId) {
        System.out.println(authorId + " " + articleId);
        int i = articlesService.deleteArticle(authorId, articleId);
        if (i > 0) {
            return Result.success("0", "删除成功！");
        } else {
            return Result.success("400", "删除失败！");
        }
    }

    //根据id查询指定文章 （用于修改数据回显和 查看单个文章使用 增加文章浏览量）
    @RequestMapping(value = "/queryByArtId/{articleId}",method = RequestMethod.GET)
    public String queryByArtId(@PathVariable Integer articleId) {
        Articles articleByArticleID = articlesService.getArticleByArticleID(articleId);
        articlesService.addarticlePageview(articleId);//增加文章浏览量
        System.out.println(articleByArticleID);
        if (articleByArticleID != null) {
            return Result.success("0", "查询成功！", articleByArticleID);
        } else {
            return Result.success("400", "查询失败！");
        }
    }
    //根据id查询指定文章 （用于修改数据回显和 查看单个文章使用 增加文章浏览量）
    @RequestMapping(value = "/queryByArtId",method = RequestMethod.POST)
    public String queryByArtId1(Integer articleId,Integer userId) {
        Articles articleByArticleID = articlesService.getArticleByArticleID(articleId);
        articlesService.addarticlePageview(articleId);//增加文章浏览量
        if (userId!=null){ //用户登录状态下才执行
            String Likestatus = articlesService.getstatus1(articleId, userId);//查询当前用户对当前文章的点赞状态
            String Favoritestatus = articlesService.getstatus2(articleId, userId);//查询当前用户对当前文章的收藏状态
            //将点赞收藏状态赋值给文章对象
            if (Likestatus!=null){
                articleByArticleID.setLikestatus(Likestatus);
            }else { //不存在说明没有点赞直接赋值为“1”
                articleByArticleID.setLikestatus("1");}
            if (Favoritestatus!=null){
                articleByArticleID.setFavoritestatus(Favoritestatus);
            }else {//不存在说明没有收藏直接赋值为“1”
                articleByArticleID.setFavoritestatus("1");}
        }
        System.out.println(articleByArticleID);
        if (articleByArticleID != null) {
            return Result.success("0", "查询成功！", articleByArticleID);
        } else {
            return Result.success("400", "查询失败！");
        }
    }

    //修改文章
    @RequestMapping("/edit")
    public String updateArticle(@ModelAttribute Articles articles) {
        System.out.println(articles);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        articles.setPublishedAt(simpleDateFormat.format(new Date()));
        int i = articlesService.updateArticle(articles);

        if (i > 0) {
            return Result.success("0", "修改成功！");
        } else {
            return Result.success("400", "修改失败！");
        }
    }

    //文章收藏
    @RequestMapping("/collection")
    public String giveaFavorites(@RequestParam("userID") Integer userID, @RequestParam("articleID") Integer articleID) {
        ArticleFavorites articleLikes1 = new ArticleFavorites(); //创建对象
        articleLikes1.setUserID(userID);
        articleLikes1.setArticleID(articleID);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        articleLikes1.setCreatedAt(simpleDateFormat.format(new Date()));
        List<ArticleFavorites> articleLikes = articlesService.getArticleFavorites(userID, articleID);
        if (articleLikes.size() > 0) { //收藏记录已存在，通过更改状态码，执行取消收藏/添加收藏
            for (ArticleFavorites articleLike : articleLikes) {
                if (articleLike.getFavoriteStatus().equals("0")) {// 0已收藏，执行取消收藏
                    articleLikes1.setFavoriteStatus("1"); //更改状态码
                    System.out.println(articleLikes1);
                    int i = articlesService.updateFavoritesStatus(articleLikes1); //取消收藏
                    int i1 = articlesService.updateFavoritesCount(articleID, 1);// 减少文章收藏量
                    if (i > 0 && i1 > 0) {
                        return Result.success("1", "取消收藏成功！");
                    } else {
                        return Result.success("400", "取消收藏失败！");
                    }
                } else {// 1取消收藏，执行添加收藏
                    articleLikes1.setFavoriteStatus("0"); //更改状态码
                    System.out.println(articleLikes1);
                    int i = articlesService.updateFavoritesStatus(articleLikes1);//添加收藏
                    int i1 = articlesService.updateFavoritesCount(articleID, 0); //增加文章收藏量
                    if (i > 0 && i1 > 0) {
                        return Result.success("0", "收藏成功！");
                    } else {
                        return Result.success("400", "收藏失败！");
                    }
                }
            }
        } else {//文章没有收藏记录，执行收藏
            int i = articlesService.addArticleFavorites(articleLikes1); //添加收藏
            int i1 = articlesService.updateFavoritesCount(articleID, 0);// 增加文章收藏量
            if (i > 0 && i1 > 0) {
                return Result.success("0", "收藏成功！");
            } else {
                return Result.success("400", "收藏失败！");
            }
        }
        return null;
    }

    //查询用户收藏夹的文章
    @RequestMapping("/selectuserFavorites")
    public String selectuserFavorites(@RequestParam("userID") Integer userID) {
        List<Articles> articles = articlesService.getuserFavorites(userID);
        System.out.println(articles);
        if (articles.size() > 0) {
            return Result.success("0", "查询文章成功", articles);
        } else {
            return Result.success("400", "查询文章失败");
        }
    }


    //  用户查询积分流水
    @RequestMapping("/selectuserIntegral")
    public String selectuserIntegral(Integer userID) {
        List<PointsLog> pointsFlow = pointsService.getPointsFlow(userID);
        if (pointsFlow.size() > 0) {
            return Result.success("0", "查询积分流水成功", pointsFlow);
        } else {
            return Result.success("400", "查询积分流水失败");
        }
    }


    //文章点赞
    @RequestMapping("/articlelike")
    public String givealike(@RequestParam("userID") Integer userID, @RequestParam("articleID") Integer articleID) {
        ArticleLikes articleLikes = new ArticleLikes(); //创建对象
        articleLikes.setUserID(userID);
        articleLikes.setArticleID(articleID);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        articleLikes.setLikedAt(simpleDateFormat.format(new Date()));
        List<ArticleLikes> articleLikes1 = articlesService.getArticleLikes(userID, articleID);
        if (articleLikes1.size() > 0) { //点赞记录已存在，通过更改状态码，执行取消点赞/添加点赞
            for (ArticleLikes articleLike : articleLikes1) {
                if (articleLike.getLikeStatus().equals("0")) {// 状态为0已点赞，执行取消点赞
                    articleLikes.setLikeStatus("1"); //更改状态码
                    int i = articlesService.updateLikesStatus(articleLikes); //取消点赞
                    int i1 = articlesService.updateLikesCount(articleID, 1);// 减少文章点赞量
                    if (i > 0 && i1 > 0) {
                        return Result.success("0", "取消点赞成功！");
                    } else {
                        return Result.success("400", "取消点赞失败！");
                    }
                } else {// 状态为1 取消点赞，执行添加点赞
                    articleLikes.setLikeStatus("0"); //更改状态码
                    System.out.println(articleLikes1);
                    int i = articlesService.updateLikesStatus(articleLikes);//添加点赞
                    int i1 = articlesService.updateLikesCount(articleID, 0); //减少文章点赞量
                    if (i > 0 && i1 > 0) {
                        return Result.success("0", "点赞成功！");
                    } else {
                        return Result.success("400", "点赞失败！");
                    }
                }
            }
        } else {//文章没有点赞记录，执行点赞
            int i = articlesService.addArticleLikes(articleLikes); //添加点赞
            int i1 = articlesService.updateLikesCount(articleID, 0);// 增加文章点赞量
            if (i > 0 && i1 > 0) {
                return Result.success("0", "点赞成功！");
            } else {
                return Result.success("400", "点赞失败！");
            }
        }
        return null;
    }

//管理员修改文章类别
    @RequestMapping("/updatesort")
    public String updatesort(ArticleSort articleSort) {
        int i = articlesService.updatesort(articleSort);
        if (i > 0) {
            return Result.success("200", "修改成功！");
        }else {
            return Result.success("400", "修改失败！");
        }
    }

    //管理员删除文章类别
    @RequestMapping("/deletesort")
    public String deltesort(ArticleSort articleSort) {
        int i = articlesService.deletesort(articleSort);
        if (i > 0) {
            return Result.success("200", "删除成功！");
        }else {
            return Result.success("400", "删除失败！");
        }
    }

    //管理员新增文章类别
    @RequestMapping("/addsort")
    public String addsort(ArticleSort articleSort) {
        int i = articlesService.addsort(articleSort);
        if (i > 0) {
            return Result.success("200", "新增成功！");
        }else {
            return Result.success("400", "新增失败！");
        }
    }

// 热门文章排序
    @RequestMapping("/sort")
    public String sort() {
        List<Articles> sort = articlesService.sort();
        if (sort!=null) {
            return Result.success("200", "查询成功！",sort);
        }else {
            return Result.success("400", "查询失败！");
        }
    }

    //管理员查询文章（全查） 集成管理员根据id查询文章
    @PostMapping("/adminshow")
    public String getAllArticles1(String queryKey, String queryDateBegin, String queryDateEnd, Integer articleSort,Integer articleID) {
        List<Articles> allArticle = articlesService.getAllArticle1(queryKey, queryDateBegin, queryDateEnd, articleSort,articleID);
        if (allArticle != null) {
            return Result.success("0", "返回文章信息成功", allArticle);
        } else {
            return Result.success("400", "返回文章信息失败");
        }
    }
    //管理员查询文章（全查） 集成管理员根据id查询文章
    @GetMapping("/adminshow/{articleID}")
    public String getAllArticles2(String queryKey, String queryDateBegin, String queryDateEnd, Integer articleSort,@PathVariable("articleID") Integer articleID) {
        List<Articles> allArticle = articlesService.getAllArticle1(queryKey, queryDateBegin, queryDateEnd, articleSort,articleID);
        if (allArticle != null) {
            return Result.success("0", "返回文章信息成功", allArticle);
        } else {
            return Result.success("400", "返回文章信息失败");
        }
    }

    //管理员删除指定用户下的指定文章
    @RequestMapping("/admin/delById")
    public String delById1(String articleStatus,Integer articleId) {
        if (articleStatus.equals("0")){ //已上架, 执行下架操作
            articleStatus="2";
           int i = articlesService.updateArticleStatus(articleStatus, articleId);
            if (i > 0) {
                return Result.success("0", "下架成功！");
            } else {
                return Result.success("400", "下架失败！");
            }
        }else if (articleStatus.equals("2")){ //已下架，执行上架操作
            articleStatus="0";
           int i = articlesService.updateArticleStatus(articleStatus, articleId);
            if (i > 0) {
                return Result.success("0", "上架成功！");
            } else {
                return Result.success("400", "上架失败！");
            }
        }
        return null;

    }

    //管理员给用户发送通知
    @RequestMapping("/admin/sendnotifications")
    public String sendnotifications(Usernotifications usernotifications) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        usernotifications.setTimestamp(simpleDateFormat.format(new Date()));
        int sendnotifications = articlesService.sendnotifications(usernotifications);
        if (sendnotifications > 0){
            return Result.success("0","发送成功！");
        }else {
            return Result.success("400","发送失败！");
        }
    }

    //用户查看个人通知

    @RequestMapping("/receivernotifications")
    public String receivernotifications(Integer userId) {
        List<Usernotifications> getnotifications = articlesService.getnotifications(userId);
        if (getnotifications!=null){
            return Result.success("0","发送成功！",getnotifications);
        }else {
            return Result.success("400","发送失败！");
        }
    }

    //用户确认个人通知
    @RequestMapping("/readnotifications")
    public String readnotifications(Integer notificationID){
        int readnotificationsed = articlesService.readnotifications(notificationID);
        if (readnotificationsed>0){
            return Result.success("0","确认成功！");
        }else {
            return Result.success("400","确认失败！");
        }

    }

//----------------------------------------------------------------------------

    //管理员查看积分规则
    @RequestMapping("/selectIntegralrule")
    public String selectIntegralrule() {
        List<PointsRules> pointsRules = pointsService.getPointsRules();
        if (pointsRules.size() > 0) {
            return Result.success("0", "查询积分规则成功", pointsRules);
        } else {
            return Result.success("400", "暂无积分规则");
        }
    }

    //管理员修改积分规则
    @RequestMapping("/updateIntegralrule")
    public String updateIntegralrule(int ruleID, int pointsValue) {
        int i = pointsService.updatePointsRules(ruleID, pointsValue);
        if (i > 0) {
            return Result.success("0", "修改成功");
        } else {
            return Result.success("400", "修改失败");
        }
    }

    //管理员手动给用户增加积分
    @RequestMapping("/manuallyaddIntegralrule")
    public String manuallyaddIntegralrule(int userID, int pointsValue) {
        int i = pointsService.manuallyaddIntegralrule(userID, pointsValue);
        if (i > 0) {
            return Result.success("0", "积分增加成功");
        } else {
            return Result.success("400", "积分增加失败");
        }
    }


    //    查看公告
    @RequestMapping("/selectnotifications")
    public String selectnotifications(Notifications notificationID){
        List<Notifications> notifications = notificationsService.selectNotifications(notificationID);
        if (notifications!=null){
            return Result.success("200","查询公告成功",notifications);
        }else {
            return Result.success("200","查询公告失败");
        }
    }

    //    发布公告
    @RequestMapping("/addnotifications")
    public String addnotifications(Notifications notifications){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        notifications.setCreatedAt(simpleDateFormat.format(new Date()));
        int i = notificationsService.addNotifications(notifications);
        if (i>0){
            return Result.success("200","发布成功");
        }else {
            return Result.success("400","发布失败");
        }
    }

    //   删除公告/
    @RequestMapping("/delnotifications")
    public String delnotifications(Notifications notifications){
        int i = notificationsService.deleteNotifications(notifications);
        if (i>0){
            return Result.success("200","删除成功");
        }else {
            return Result.success("400","删除失败");
        }
    }











}
